<template>
  <div class="report-container">
    <div class="search-button">
      <el-button type="primary" @click="handleAddSave"
        ><img src="@/assets/images/Submit.png" alt="" /> 提交</el-button
      >
      <el-button @click="handleBack" color="#efbf00"
        ><img src="@/assets/images/back.png" alt="" />
        <span style="color: #ffffff">返回</span>
      </el-button>
    </div>
    <div class="detail-top">
      <div class="detial-text">
        <div class="detial-title">
          <div class="title-top">
            <img src="@/assets/images/title-card.png" alt="" />
            <div class="title">
              {{ detaildata.name }}
            </div>
            <div class="tabs">
              <div class="tab">{{ detaildata.industryName }}</div>
              <div class="tab">{{ detaildata.institutionType }}</div>
            </div>
          </div>
          <div class="title-bottom">
            <div class="bottom-item">
              <div class="item-title">详细地址：</div>
              <div class="item-content">{{ detaildata.address || "--" }}</div>
            </div>
            <div class="bottom-item">
              <div class="item-title">检查单位：</div>
              <div class="item-content">{{ detaildata.policeStationName }}</div>
            </div>
            <div class="bottom-item">
              <div class="item-title">来源：</div>
              <div class="item-content">{{ detaildata.taskSourceName }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="report-form">
      <div class="middle-top">
        <div class="middle-title">
          <img src="@/assets/images/title-icon.png" alt="" />
          检查事项（必填）
        </div>
      </div>

      <el-form
        :model="detaildata"
        ref="reportFormRef"
        :rules="queryRules"
        label-width="130px"
        label-position="top"
      >
        <el-row v-for="(item, index) in detaildata.questionVOS" :key="index">
          <el-col :span="24">
            <div class="form-item-style">
              <div class="first-item">
                <el-form-item
                  :label="item.questionLabel"
                  :prop="`questionVOS.${index}.standardOrNot`"
                  :rules="[
                    {
                      required: true,
                      message: '请选择是否达标',
                      trigger: 'change',
                    },
                  ]"
                  label-width="130"
                >
                  <el-radio-group v-model="item.standardOrNot">
                    <el-radio :label="0">是，已达标</el-radio>
                    <el-radio :label="1">否，未达标</el-radio>
                  </el-radio-group>
                </el-form-item>
              </div>
              <div class="item-style" v-if="item.standardOrNot == 1">
                <el-form-item
                  :prop="`questionVOS.${index}.description`"
                  :rules="[
                    {
                      required: true,
                      message: '请输入存在的问题及其他情况',
                      trigger: 'blur',
                    },
                  ]"
                  label-width="130"
                >
                  <el-input
                    v-model="item.description"
                    placeholder="请填写存在的问题及其他情况（必填）"
                    clearable
                    maxlength="20"
                    class="style-input"
                  />
                </el-form-item>
                <el-form-item
                  :prop="`questionVOS.${index}.lackItemList`"
                  :rules="[
                    {
                      required: true,
                      message: '请选择缺少的项',
                      trigger: 'change',
                    },
                  ]"
                  label-width="130"
                  v-if="item.questionDetailList"
                >
                  <div class="iptcbx">
                    <el-checkbox-group v-model="item.lackItemList">
                      <el-checkbox
                        v-for="(jtem, i) in item.questionDetailList"
                        :key="i"
                        :label="String(jtem.questionDetailId)"
                      >
                        {{ jtem.questionDetailLabel }}
                      </el-checkbox>
                    </el-checkbox-group>
                  </div>
                </el-form-item>
              </div>
            </div>
          </el-col>
        </el-row>

        <div class="middle-top">
          <div class="middle-title">
            <img src="@/assets/images/title-icon.png" alt="" />
            现场照片（必填）
          </div>
        </div>

        <div class="form-upload">
          <div>
            <el-upload
              ref="uploadRef"
              :action="uploadUrl"
              :show-file-list="false"
              accept=".png,.jpg,.jpeg"
              :limit="10"
              multiple
              :headers="myHeaders"
              :on-success="uploadSuccess"
              :before-upload="beforeUpload"
            >
              <img
                src="@/assets/images/upload-images.png"
                alt=""
                ref="imgRef"
              />
            </el-upload>
            <el-progress
              v-if="isUpload"
              status="success"
              :percentage="100"
              :format="format"
              :indeterminate="true"
              style="width: 80%"
            />
          </div>

          <div class="tooltip">
            <span>请上传JPG/PNG/JPEG格式文件</span>
            <span>建议大小小于5M</span>
            <span>最多上传10张</span>
          </div>
        </div>
        <div class="upload-pics">
          <div class="pic" v-for="(item, index) in picList" :key="index">
            <img :src="item.url" :alt="item.name" />
            <div class="operate">
              <span style="cursor: pointer" @click="replacepic(index)"
                >替换</span
              >
              <span>|</span>
              <span style="cursor: pointer" @click="delpic(index)">删除</span>
            </div>
          </div>
        </div>
        <div class="middle-top">
          <div class="middle-title">
            <img src="@/assets/images/title-icon.png" alt="" />
            检查纪实
          </div>
        </div>

        <el-form-item label="" prop="checkContent" label-width="130">
          <el-input
            v-model="detaildata.checkContent"
            type="textarea"
            rows="6"
            maxlength="500"
            placeholder="请输入内容"
          ></el-input>
        </el-form-item>
      </el-form>

      <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" />
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import {
  getCheckQuestionnaire,
  updateTaskDetail,
  gettaskdetail,
  addSelfCheckTask,
} from "@/api/task/task";
import { getToken } from "@/utils/auth";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
const router = useRouter();

const emit = defineEmits(["refreshList"]);

let detaildata = ref({});

let reportForm = ref({
  checkList: ref([]),
});

let picList = ref([]);

const queryRules = ref({
  standardOrNot: [
    { required: true, message: "请输入小组名称", trigger: "blur" },
  ],
});
let isUpload = ref(false);

//上传图片的地址
const uploadUrl = import.meta.env.VITE_APP_BASE_API + "/file/upload";

const myHeaders = ref({
  Authorization: "Bearer " + getToken(),
});

const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const disabled = ref(false);

const handleRemove = (file) => {
  console.log(file);
};

const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url;
  dialogVisible.value = true;
};

const handleDownload = (file) => {
  console.log(file);
};

//上传的状态
let uploadstatus = ref("add");
let replaceindex = ref(0);
let indexToReplace = ref(0);
const format = (percentage) =>
  percentage === 100 ? "上传中……" : `${percentage}%`;
const uploadSuccess = (res) => {
  console.log("chenggon", res);
  if (res.code == 200) {
    ElMessage.success("图片上传成功！");
    isUpload.value = false;
    if (uploadstatus.value == "add") {
      picList.value.push(res.data);
    } else {
      picList.value.splice(indexToReplace.value, 1, res.data);
      uploadstatus.value = "add";
    }
  } else {
    isUpload.value = false;
    ElMessage.error(`文件上传失败！`);
  }
};

function beforeUpload(file) {
  console.log("file", file);
  if (file.name.length > 50) {
    ElMessage.error(`文件名过长！最多只能上传50个文字的文件名文件！`);
    return false;
  }
  isUpload.value = true;
}
/**
 * @description: 替换图片
 */
let uploadRef = ref(null);
const replacepic = (index) => {
  uploadstatus.value = "replace";
  indexToReplace.value = index;
  uploadRef.value.$el.querySelector("input").click();
};

/**
 * @description: 删除图片
 */
const delpic = (index) => {
  picList.value.splice(index, 1);
};

/**
 * @description: 提交
 * @param {Object} customerFormRef 客户表单引用
 */
const reportFormRef = ref(null);
const handleAddSave = async () => {
  await reportFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      ElMessageBox.confirm("确定保存以上数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
      })
        .then(async () => {
          if (picList.value.length == 0) {
            return ElMessage.error("请上传现场图片！");
          }
          let obj = {
            answerItemList: detaildata.value.questionVOS,
            fileVos: picList.value,
            taskDetailReqVO: {
              checkContent: detaildata.value.checkContent,
              checkName: checkName.value,
              taskId: detaildata.value.taskId,
              checkDate: detaildata.value.checkDate,
              policeStationId: detaildata.value.policeStationId,
              institutionId: detaildata.value.institutionId,
              taskSource: router.currentRoute.value.path == "/erp" ? 3 : "",
              institutionName: detaildata.value.name,
            },
          };
          let Func;
          if (router.currentRoute.value.path == "/erp") {
            Func = addSelfCheckTask;
          } else {
            Func = updateTaskDetail;
          }
          Func(obj).then((res) => {
            if (res.code == 200) {
              emit("update:showcheckreport", false);
              emit("refreshList", 1);
              ElMessage.success(res.msg);
              detaildata.value = {};
            }
          });
        })
        .catch(() => {});
    }
  });
};
//处理返回
const handleBack = () => {
  emit("update:showcheckreport", false);
};

//处理检查
let rowdata = ref({});
const handleReport = (row) => {
  rowdata.value = row;
  getCheckQuestionnaire({
    taskId: row.taskId,
    institutionId: row.institutionId,
  }).then((res) => {
    detaildata.value = res.data;
  });
};
//处理编辑
let checkName = ref("");
const handleEditReport = (row) => {
  console.log("zhixing");
  handleReport(row);
  setTimeout(() => {
    gettaskdetail(row.taskId).then((res) => {
      console.log("detaildata.value", detaildata.value);
      detaildata.value.questionVOS = res.data.questionAnswerList;
      picList.value = res.data.fileList;
      detaildata.value.checkContent = res.data.checkContent;
      checkName.value = res.data.checkName;
    });
  }, 500);
};

defineExpose({
  handleReport,
  handleEditReport,
});
</script>

<style scoped lang="scss">
.report-container {
  background-color: #ffffff;
  border-radius: 10px;
  padding: 10px 30px 20px 30px;
  height: 81vh;
  overflow-y: scroll;
  .detail-top {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .detial-text {
      display: flex;

      .detial-title {
        display: flex;
        flex-direction: column;
        .title-top {
          display: flex;
          align-items: center;
          margin-bottom: 25px;
          font-weight: 600;
          img {
            transform: translateY(1px);
            margin-right: 10px;
          }
          .title {
            font-size: 16px;
            color: #000000;
            margin-right: 50px;
          }
          .tabs {
            display: flex;
            font-size: 14px;
            .tab {
              padding: 4px 8px;
              color: #ffffff;
              margin-right: 10px;
            }
            .tab:nth-child(1) {
              background-color: #088ef8;
            }
            .tab:nth-child(2) {
              background-color: #e2a802;
            }
          }
        }
        .title-bottom {
          display: flex;
          width: 100%;
          font-size: 14px;
          color: #666666;
          .bottom-item {
            display: flex;
            margin-right: 40px;
          }
        }
      }
    }
  }
  .report-form {
    .middle-top {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 20px 0;
    }
    .form-item-style {
      display: flex;
      width: 100%;
      border-bottom: 1px solid #f4f4f4;
      padding: 10px 0;
      .first-item {
        width: 400px;
      }
      .item-style {
        width: 75%;
        padding-bottom: 8px;
        transform: translateY(30px);
        :deep(.el-radio-group) {
          width: 25%;
        }
        :deep(.el-checkbox-group) {
          width: 100%;
        }
      }
    }
    .form-upload {
      display: flex;
      .tooltip {
        display: flex;
        justify-content: space-between;
        flex-direction: column;
        height: 66px;
        font-size: 14px;
        color: #999999;
        margin-left: 20px;
      }
    }
    .upload-pics {
      display: flex;
      margin-top: 20px;
      .pic {
        position: relative;
        width: 160px;
        height: 100px;
        display: flex;
        justify-content: center;
        margin-right: 10px;
        img {
          width: 100%;
          height: 100%;
        }
        .operate {
          display: flex;
          align-items: center;
          justify-content: space-around;
          position: absolute;
          bottom: 10px;
          margin: 0 auto;
          font-size: 14px;
          background: rgba(0, 0, 0, 0.4);
          color: #fff;
          width: 120px;
          height: 30px;
        }
      }
    }
    :deep(.el-radio__input.is-checked .el-radio__inner) {
      background-color: #5eb1f0;
    }
    :deep(.el-radio__input.is-checked + .el-radio__label) {
      color: #5aa4dd !important;
    }
    :deep(.el-form-item--default .el-form-item__content) {
    }
    :deep(.el-upload--picture-card) {
      --el-upload-picture-card-size: unset;
    }
    :deep(.el-upload-list--picture-card) {
      --el-upload-picture-card-size: unset;
      width: 120px;
      height: 60px;
      img {
        width: 100%;
        height: 100%;
      }
    }
  }
}
</style>
